package com.fqgame.user.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ配置类
 */
@Configuration
public class RabbitMQConfig {

    /**
     * 用户积分交换机
     */
    @Bean
    public DirectExchange userPointsExchange() {
        return new DirectExchange("user.points");
    }

    /**
     * 用户积分队列
     */
    @Bean
    public Queue userPointsQueue() {
        return new Queue("user.points.queue", true);
    }

    /**
     * 用户积分绑定
     */
    @Bean
    public Binding userPointsBinding() {
        return BindingBuilder.bind(userPointsQueue())
                .to(userPointsExchange())
                .with("user.points.update");
    }

    /**
     * 订单通知队列
     */
    @Bean
    public Queue orderNotifyQueue() {
        return new Queue("order.notify.queue", true);
    }

    /**
     * 订单通知交换机
     */
    @Bean
    public DirectExchange orderNotifyExchange() {
        return new DirectExchange("order.notify");
    }

    /**
     * 订单通知绑定
     */
    @Bean
    public Binding orderNotifyBinding() {
        return BindingBuilder.bind(orderNotifyQueue())
                .to(orderNotifyExchange())
                .with("order.created");
    }

    /**
     * 消息转换器
     */
    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * RabbitTemplate配置
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }
}